package com.evil.common.core.util;

import java.text.Collator;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liyang
 * @date 2025-01-19 13:00
 */
public class ComparatorUtil {
    private final static Pattern splitPattern = Pattern.compile("(\\d+)|(\\D+)");
    private final static Collator collator;

    static {
        collator = Collator.getInstance(Locale.CHINA);
        // 设置比较强度为PRIMARY，忽略大小写和重音符号
        collator.setStrength(Collator.PRIMARY);
    }

    public static int compareChinese(String s1, String s2) {
        Matcher m1 = splitPattern.matcher(s1);
        Matcher m2 = splitPattern.matcher(s2);

        while (m1.find() && m2.find()) {
            if (m1.group(1) != null && m2.group(1) != null) {
                int num1 = Integer.parseInt(m1.group(1));
                int num2 = Integer.parseInt(m2.group(1));
                if (num1 != num2) {
                    return Integer.compare(num1, num2);
                }
            } else if (m1.group(2) != null && m2.group(2) != null) {
                int result = collator.compare(m1.group(2), m2.group(2));
                if (result != 0) {
                    return result;
                }
            } else {
                return m1.group() == null ? -1 : 1;
            }
        }

        return m1.hitEnd() && m2.hitEnd() ? 0 : m1.hitEnd() ? -1 : 1;
    }
}
